package com.neusoft.bizcore.auth.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.auth.dto.AuthPermissionDTO;
import com.neusoft.bizcore.auth.model.AuthContentType;
import com.neusoft.bizcore.auth.model.AuthPermission;
import com.neusoft.bizcore.auth.repository.AuthContentTypeRepository;
import com.neusoft.bizcore.auth.repository.AuthPermissionRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class AuthPermissionConverter extends AbstractConverter<AuthPermission, AuthPermissionDTO> {

    @Autowired
    private AuthPermissionRepository authPermissionRepository;
    @Autowired
    private AuthContentTypeRepository authContentTypeRepository;
    @Autowired
    private AuthContentTypeConverter authContentTypeConverter;

    @Override
    public AuthPermission toModel(final AuthPermissionDTO dto) {
        AuthPermission model;
        if (dto.isNew()) {
            model = new AuthPermission();
        } else {
            model = this.authPermissionRepository.getOne(dto.getId());
        }
        model.setName(dto.getName());
        model.setCode(dto.getCode());
        model.setType(dto.getType());
        if (null != dto.getContentTypeId()) {
            final AuthContentType authContentType = this.authContentTypeRepository.getOne(dto.getContentTypeId());
            model.setContentType(authContentType);
        } else {
            model.setContentType(null);
        }
        return model;
    }

    @Override
    public AuthPermissionDTO toDTO(final AuthPermission model, final boolean forListView) {
        final AuthPermissionDTO dto = new AuthPermissionDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        dto.setType(model.getType());
        if (null != model.getContentType()) {
            dto.setContentTypeId(model.getContentType().getId());
            dto.setContentType(this.authContentTypeConverter.toDTO(model.getContentType()));
        }
        return dto;
    }

}
